package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.LeXiangTongUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 乐享通
 */
@Service
public class LeXiangTongPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String apiSecret = pushApiKeyParam.getApiSecret();
        String apiKey = pushApiKeyParam.getApiKey();

        String province = memberSourceInfo.getProvince();

        if (StrUtil.endWith(province, "省") || StrUtil.endWith(province, "市")) {
            province = memberSourceInfo.getProvince().substring(0, memberSourceInfo.getProvince().length() - 1);
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phoneMd5", memberSourceInfo.getMobileMd5());
        paramMap.put("job_type", LeXiangTongUtil.getGongZuoType(memberSourceInfo.getGongzuo()));
        paramMap.put("local_fund", LeXiangTongUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("age", memberSourceInfo.getAge());
        paramMap.put("pid", province);

        String dataString = LeXiangTongUtil.encrypt(JSON.toJSONString(paramMap),apiSecret,apiKey);

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("data", dataString);

        log.info("【乐享通】撞库开始【queryUrl】{}【paramMap】{}【bizMap】{}", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【乐享通】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
            String status = data.getString("status");
            pushApiResult.setCode(code + "|" + status);
            if (StrUtil.equals(String.valueOf(status), "0")) {
                pushApiResult.setPushSuccess(true);
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String apiSecret = pushApiKeyParam.getApiSecret();
        String apiKey = pushApiKeyParam.getApiKey();
        String province = memberSourceInfo.getProvince();

        if (StrUtil.endWith(province, "省") || StrUtil.endWith(province, "市")) {
            province = memberSourceInfo.getProvince().substring(0, memberSourceInfo.getProvince().length() - 1);
        }
        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("name", memberSourceInfo.getRealname());
        if (StringUtils.isNotEmpty(memberSourceInfo.getIdcard())){
            bizMap.put("idcard", memberSourceInfo.getIdcard());
        }
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 2);
        bizMap.put("age", String.valueOf(memberSourceInfo.getAge()));
        bizMap.put("mobile", memberSourceInfo.getMobile());
        bizMap.put("degree", LeXiangTongUtil.getXueLi(memberSourceInfo.getXueli()));
        bizMap.put("job", LeXiangTongUtil.getGongZuo(memberSourceInfo.getGongzuo()));
        bizMap.put("job_type", LeXiangTongUtil.getGongZuoType(memberSourceInfo.getGongzuo()));
        bizMap.put("seniority", 2);
        bizMap.put("local_fund", LeXiangTongUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("local_social", LeXiangTongUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("local_house", LeXiangTongUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("local_car", LeXiangTongUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("credit_card", LeXiangTongUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("local_ensure", LeXiangTongUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("loan_money", LeXiangTongUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loan_period", LeXiangTongUtil.getloan(memberSourceInfo.getLoanTime()));
        bizMap.put("loan_purpose", LeXiangTongUtil.getPurpose(memberSourceInfo.getYongtu()));
        bizMap.put("pid", province);
        bizMap.put("cid", memberSourceInfo.getCity());
        bizMap.put("job_income", LeXiangTongUtil.getShouRu(memberSourceInfo.getShouru()));
        bizMap.put("zhimascore", LeXiangTongUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("income_type", 1);
        bizMap.put("wld", 1);
        bizMap.put("launch_mode", 1);

        String data = LeXiangTongUtil.encrypt(JSON.toJSONString(bizMap),apiSecret,apiKey);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("data", data);

        log.info("【乐享通】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【乐享通】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }


}
